﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using HtmlAgilityPack;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace VH.SharePoint.Api.Helpers
{
    public static class WikiPageHelper
    {
        private static string ConvertAnchorsToWikiLinks(this string html)
        {
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();

            htmlDoc.LoadHtml(html);

            var anchorTags = (from d in htmlDoc.DocumentNode.Descendants()
                              where d.Attributes.Contains("class") && d.Attributes["class"].Value == "ms-wikilink"
                              select d).ToList();

            foreach (var anchor in anchorTags)
            {
                // Two kinds of links
                // [[Direct Link]]
                // [[Wiki Page Name|Display Name]]
                var wikiPageFromLink =  HttpUtility.UrlDecode(anchor.Attributes["href"].Value.Split('/').LastOrDefault().Replace(".aspx", ""));
                var wikiPageFromText = anchor.InnerText;

                HtmlNode textNode = null;

                if (wikiPageFromLink == wikiPageFromText)
                {
                    // Simple link
                    textNode = HtmlTextNode.CreateNode("[[" + wikiPageFromText + "]]");
                }
                else
                {
                    // Substituted link
                    textNode = HtmlTextNode.CreateNode(String.Format("[[{0}|{1}]]", wikiPageFromLink, wikiPageFromText));
                }

                if (textNode != null)
                {
                    anchor.ParentNode.ReplaceChild(textNode, anchor);
                }
            }

            return htmlDoc.DocumentNode.InnerHtml;
        }

        public static string GetHtmlEditableContent(string html)
        {
            if (string.IsNullOrEmpty(html)) return string.Empty;
            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(html);

            HtmlNode divNode = (from d in htmlDoc.DocumentNode.Descendants()
                                where d.Attributes.Contains("class") && d.Attributes["class"].Value == "ms-rte-layoutszone-inner"
                                select d).FirstOrDefault();
            HtmlNode divNode2 = (from d in htmlDoc.DocumentNode.Descendants()
                                 where d.Attributes.Contains("class") && d.Attributes["class"].Value.StartsWith("ExternalClass")
                                 select d).FirstOrDefault();

            if (divNode != null)
            {
                // SP 2010
                return divNode.InnerHtml;
            }
            else if (divNode2 != null)
            {
                // SP 2007 or something else
                return divNode2.InnerHtml.ConvertAnchorsToWikiLinks();
            }
            else
            {
                return null;
            }
        }
        public static string InsertSharepointHtmlWrapper(string html)
        {
            if (string.IsNullOrEmpty(html)) return string.Empty;
            // No weird wrapper HTML for 2007
            if (SPContext.Current.Web.UIVersion<4)
                return Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(html);

            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(@"<table id='layoutsTable' style='width:100%'>
                            <tbody>
                                <tr>
                                    <td>
                                        <div class='ms-rte-layoutszone-outer' style='width:99.9%'>
                                            <div class='ms-rte-layoutszone-inner' style='min-height:60px;word-wrap:break-word'>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <span id='layoutsData' style='display:none'>false,false,1</span>");

            HtmlNode divNode = (from d in htmlDoc.DocumentNode.Descendants()
                                where d.Attributes.Contains("class") && d.Attributes["class"].Value == "ms-rte-layoutszone-inner"
                                select d).FirstOrDefault();

            divNode.InnerHtml = Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(html);

            return htmlDoc.DocumentNode.InnerHtml;
        }
    }
}
